<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true">
            <el-form-item label="项目名称" prop="proName">
              <el-input v-model="queryParams.proName" placeholder="请输入项目名称" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="项目类型" prop="proType">
              <el-select v-model="queryParams.proType" placeholder="请选择项目类型" clearable>
                <el-option v-for="dict in project_type" :key="dict.value" :label="dict.label" :value="dict.value" />
              </el-select>
            </el-form-item>
            <el-form-item label="项目状态" prop="proStatus">
              <el-select v-model="queryParams.proStatus" placeholder="请选择项目状态" clearable>
                <el-option v-for="dict in contract_status" :key="dict.value" :label="dict.label" :value="dict.value" />
              </el-select>
            </el-form-item>
            <el-form-item label="负责人" prop="proLeadersId">
              <el-select
                :model-value="selectedSearchLeader ? selectedSearchLeader.userName || selectedSearchLeader.nickName : ''"
                placeholder="请选择项目负责人"
                style="width: 240px"
                clearable
                @click="showSearchLeaderSelector = true"
                @clear="clearSearchLeader"
              >
                <template #empty>
                  <div style="text-align: center; padding: 10px">
                    <el-button type="primary" plain @click="showSearchLeaderSelector = true"> 选择项目负责人 </el-button>
                  </div>
                </template>
              </el-select>
            </el-form-item>
            <el-form-item label="执行总裁" prop="proPresidentsId">
              <el-select
                :model-value="selectedSearchPresident ? selectedSearchPresident.userName || selectedSearchPresident.nickName : ''"
                placeholder="请选择项目执行总裁"
                style="width: 240px"
                clearable
                @click="showSearchPresidentSelector = true"
                @clear="clearSearchPresident"
              >
                <template #empty>
                  <div style="text-align: center; padding: 10px">
                    <el-button type="primary" plain @click="showSearchPresidentSelector = true"> 选择项目执行总裁 </el-button>
                  </div>
                </template>
              </el-select>
            </el-form-item>
            <el-form-item label="创建时间" prop="createTime" style="width: 308px">
              <el-date-picker
                v-model="dateRange"
                value-format="YYYY-MM-DD HH:mm:ss"
                type="daterange"
                range-separator="-"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                :default-time="[new Date(2000, 1, 1, 0, 0, 0), new Date(2000, 1, 1, 23, 59, 59)]"
                style="width: 100%"
              ></el-date-picker>
            </el-form-item>
            <el-form-item style="margin-left: auto">
              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-dropdown @command="handleMoreCommand" v-hasPermi="['project:flow:import', 'project:flow:export']">
              <el-button type="warning" plain size="default">
                导入导出
                <el-icon class="el-icon--right">
                  <ArrowDown />
                </el-icon>
              </el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item command="download-template">
                    <el-icon style="vertical-align: middle">
                      <Download />
                    </el-icon>
                    <span style="margin-left: 4px">下载模板</span>
                  </el-dropdown-item>
                  <el-dropdown-item command="import-data">
                    <el-icon style="vertical-align: middle">
                      <Upload />
                    </el-icon>
                    <span style="margin-left: 4px">导入数据</span>
                  </el-dropdown-item>
                  <el-dropdown-item command="export-data">
                    <el-icon style="vertical-align: middle">
                      <Download />
                    </el-icon>
                    <span style="margin-left: 4px">导出数据</span>
                  </el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </el-col>
          <!-- 排序控件 -->
          <el-col :span="12" style="display: flex; align-items: center; gap: 8px">
            <el-select v-model="sortField" placeholder="选择排序字段" clearable style="width: 170px" @change="handleSortChange">
              <el-option label="项目名称" value="proName" />
              <el-option label="项目编号" value="proNumber" />
              <el-option label="项目类型" value="proType" />
              <el-option label="项目状态" value="proStatus" />
              <el-option label="项目负责人" value="proLeadersName" />
              <el-option label="项目执行总裁" value="proPresidentsName" />
              <el-option label="创建人" value="createBy" />
              <el-option label="创建时间" value="createTime" />
              <el-option label="绩效审核状态" value="flowStatus" />
            </el-select>
            <el-button
              v-if="sortField"
              :icon="sortOrder === 'asc' ? 'ArrowUp' : 'ArrowDown'"
              @click="toggleSortOrder"
              type="info"
              plain
              size="small"
              :title="sortOrder === 'asc' ? '当前为正序，点击切换为逆序' : '当前为逆序，点击切换为正序'"
            >
              {{ sortOrder === 'asc' ? '正序' : '逆序' }}
            </el-button>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table v-loading="loading" :data="projectList" border>
        <!-- 序号 -->
        <el-table-column label="序号" align="center" width="80">
          <template #default="scope">
            <span>{{ (queryParams.pageNum - 1) * queryParams.pageSize + scope.$index + 1 }}</span>
          </template>
        </el-table-column>
        <el-table-column label="项目名称" align="center" prop="proName" show-overflow-tooltip />
        <el-table-column label="项目编号" align="center" prop="proNumber" />
        <el-table-column label="项目类型" align="center" prop="proType" width="180">
          <template #default="scope">
            <dict-tag :options="project_type" :value="scope.row.proType" />
          </template>
        </el-table-column>
        <el-table-column label="项目负责人" align="center" prop="proLeadersName" width="180" show-overflow-tooltip />
        <el-table-column label="项目执行总裁" align="center" prop="proPresidentsName" width="180" show-overflow-tooltip />
        <el-table-column label="创建人" align="center" prop="createBy" width="150" />
        <el-table-column label="创建时间" align="center" prop="createTime" width="150">
          <template #default="scope">
            {{ scope.row.createTime ? parseTime(scope.row.createTime, '{y}-{m}-{d} {h}:{i}:{s}') : '' }}
          </template>
        </el-table-column>
        <el-table-column label="项目状态" align="center" prop="proStatus" width="120">
          <template #default="scope">
            <dict-tag :options="contract_status" :value="scope.row.proStatus" />
          </template>
        </el-table-column>
        <el-table-column label="绩效审核状态" align="center" prop="flowStatus" width="120">
          <template #default="scope">
            <dict-tag :options="approval_commit_status" :value="scope.row.flowStatus || ''" />
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="120" class-name="small-padding fixed-width">
          <template #default="scope">
            <!-- 如果当前用户是项目负责人，显示拆分计划按钮 -->
            <el-tooltip v-if="isCurrentUserLeader(scope.row)" content="拆分计划" placement="top">
              <el-button type="primary" link class="icon-button" @click="handleSplit(scope.row)">
                <el-icon>
                  <Operation />
                </el-icon>
              </el-button>
            </el-tooltip>

            <!-- 如果当前用户不是项目负责人，显示查看计划按钮 -->
            <el-tooltip v-else content="查看计划" placement="top">
              <el-button type="info" link class="icon-button" @click="handleViewPlan(scope.row)">
                <el-icon>
                  <View />
                </el-icon>
              </el-button>
            </el-tooltip>

            <!-- 如果当前用户是项目执行总裁，显示通知负责人按钮 -->
            <el-tooltip v-if="isCurrentUserPresident(scope.row)" content="通知负责人" placement="top">
              <el-button type="warning" link class="icon-button" @click="handleNotifyLeader(scope.row)">
                <el-icon>
                  <Bell />
                </el-icon>
              </el-button>
            </el-tooltip>
          </template>
        </el-table-column>
        <template #empty>
          <el-empty description="暂无项目数据" />
        </template>
      </el-table>

      <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList" />
    </el-card>

    <!-- 项目负责人选择对话框 -->
    <UserSelector
      v-model:visible="showSearchLeaderSelector"
      title="选择项目负责人"
      :multiple="false"
      :selectedUserIds="queryParams.proLeadersId"
      :selectedUserNames="selectedSearchLeaderName"
      @confirmWithIds="handleSearchLeaderConfirm"
      @cancel="handleSearchLeaderCancel"
    />

    <!-- 项目执行总裁选择对话框 -->
    <UserSelector
      v-model:visible="showSearchPresidentSelector"
      title="选择项目执行总裁"
      :multiple="false"
      :selectedUserIds="queryParams.proPresidentsId"
      :selectedUserNames="selectedSearchPresidentName"
      @confirmWithIds="handleSearchPresidentConfirm"
      @cancel="handleSearchPresidentCancel"
    />

    <!-- 导入对话框 -->
    <el-dialog v-model="upload.open" :title="upload.title" width="400px" append-to-body>
      <el-upload
        ref="uploadRef"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <el-icon class="el-icon--upload">
          <UploadFilled />
        </el-icon>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <template #tip>
          <div class="text-center el-upload__tip">
            <span>仅允许导入xls、xlsx格式文件。</span>
            <el-link type="primary" :underline="false" style="font-size: 12px; vertical-align: baseline" @click="handleImportTemplate"
              >下载模板</el-link
            >
          </div>
        </template>
      </el-upload>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitFileForm">确 定</el-button>
          <el-button @click="upload.open = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { planPageList } from '@/api/project/init/proInfo';
import { useRouter } from 'vue-router';
import UserSelector from '@/components/UserSelector/index.vue';
import { useUserStore } from '@/store/modules/user';
import { ArrowUp, ArrowDown, Download, Upload, UploadFilled, View } from '@element-plus/icons-vue';
import { globalHeaders } from '@/utils/request';
import { ElMessageBox } from 'element-plus';

const { proxy } = getCurrentInstance();
const router = useRouter();
const userStore = useUserStore();
const { project_type, contract_status, approval_commit_status } = toRefs<any>(
  proxy?.useDict('project_type', 'contract_status', 'approval_commit_status')
);

const loading = ref(false);
const showSearch = ref(true);
const projectList = ref([]);
const total = ref(0);
const dateRange = ref<[DateModelType, DateModelType]>(['', '']);

const queryFormRef = ref<ElFormInstance>();

const queryParams = ref({
  pageNum: 1,
  pageSize: 10,
  proName: undefined,
  proType: undefined,
  proStatus: undefined,
  proLeadersId: undefined,
  proPresidentsId: undefined,
  orderByColumn: undefined,
  isAsc: undefined,
  params: {}
});

// 搜索相关的状态变量
const selectedSearchLeader = ref(null);
const selectedSearchLeaderName = ref('');
const showSearchLeaderSelector = ref(false);
const selectedSearchPresident = ref(null);
const selectedSearchPresidentName = ref('');
const showSearchPresidentSelector = ref(false);

// 排序相关的状态变量
const sortField = ref<string | undefined>(undefined);
const sortOrder = ref<string>('asc'); // 设置默认为正序

// 导入相关
const uploadRef = ref();
const upload = reactive({
  // 是否显示弹出层
  open: false,
  // 弹出层标题
  title: '',
  // 是否禁用上传
  isUploading: false,
  // 设置上传的请求头部
  headers: globalHeaders(),
  // 上传的地址
  url: import.meta.env.VITE_APP_BASE_API + '/pro/flow/importData'
});

const formatAmount = (amount) => {
  if (amount === null || amount === undefined) return '0.00';
  return Number(amount).toLocaleString('zh-CN', {
    minimumFractionDigits: 2,
    maximumFractionDigits: 2
  });
};

const getList = async () => {
  loading.value = true;
  try {
    const params = { ...queryParams.value };
    // 使用工具类处理创建时间范围
    proxy?.addDateRange(params, dateRange.value, 'CreateTime');
    // 添加排序参数
    if (sortField.value && sortOrder.value) {
      params.orderByColumn = sortField.value;
      params.isAsc = sortOrder.value;
    }
    const res = await planPageList(params);
    projectList.value = res.rows;
    total.value = res.total;
  } catch (error) {
    ElMessage.error('获取项目列表失败');
  } finally {
    loading.value = false;
  }
};

const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};

const resetQuery = () => {
  dateRange.value = ['', ''];
  queryFormRef.value?.resetFields();
  queryParams.value.params = {};
  // 重置搜索相关状态
  selectedSearchLeader.value = null;
  selectedSearchLeaderName.value = '';
  selectedSearchPresident.value = null;
  selectedSearchPresidentName.value = '';
  queryParams.value.proLeadersId = undefined;
  queryParams.value.proPresidentsId = undefined;
  // 重置排序状态
  sortField.value = undefined;
  sortOrder.value = 'asc';
  handleQuery();
};

// 项目负责人搜索相关方法
const handleSearchLeaderConfirm = (data) => {
  if (data.users && data.users.length > 0) {
    selectedSearchLeader.value = data.users[0];
    selectedSearchLeaderName.value = data.userNames || '';
    queryParams.value.proLeadersId = data.userIds || '';
  } else {
    selectedSearchLeader.value = null;
    selectedSearchLeaderName.value = '';
    queryParams.value.proLeadersId = undefined;
  }
  showSearchLeaderSelector.value = false;
};

const handleSearchLeaderCancel = () => {
  showSearchLeaderSelector.value = false;
};

const clearSearchLeader = () => {
  selectedSearchLeader.value = null;
  selectedSearchLeaderName.value = '';
  queryParams.value.proLeadersId = undefined;
};

// 项目执行总裁搜索相关方法
const handleSearchPresidentConfirm = (data) => {
  if (data.users && data.users.length > 0) {
    selectedSearchPresident.value = data.users[0];
    selectedSearchPresidentName.value = data.userNames || '';
    queryParams.value.proPresidentsId = data.userIds || '';
  } else {
    selectedSearchPresident.value = null;
    selectedSearchPresidentName.value = '';
    queryParams.value.proPresidentsId = undefined;
  }
  showSearchPresidentSelector.value = false;
};

const handleSearchPresidentCancel = () => {
  showSearchPresidentSelector.value = false;
};

const clearSearchPresident = () => {
  selectedSearchPresident.value = null;
  selectedSearchPresidentName.value = '';
  queryParams.value.proPresidentsId = undefined;
};

const handleSplit = (row) => {
  router.push(`/project/flow-split/index/${row.id}`);
};

// 查看计划功能
const handleViewPlan = (row) => {
  router.push(`/project/flow-split/index/${row.id}`);
};

// 判断当前用户是否为项目负责人
const isCurrentUserLeader = (row) => {
  if (!row.proLeadersId || !userStore.userId) return false;
  const leaderIds = row.proLeadersId
    .toString()
    .split(',')
    .map((id) => id.trim());
  return leaderIds.includes(userStore.userId.toString());
};

// 判断当前用户是否为项目执行总裁
const isCurrentUserPresident = (row) => {
  if (!row.proPresidentsId || !userStore.userId) return false;
  const presidentIds = row.proPresidentsId
    .toString()
    .split(',')
    .map((id) => id.trim());
  return presidentIds.includes(userStore.userId.toString());
};

// 通知负责人功能（暂时只显示消息）
const handleNotifyLeader = (row) => {
  ElMessage.info('通知负责人功能待实现');
};

// 排序相关方法
const handleSortChange = (value: string) => {
  sortField.value = value;
  if (sortOrder.value !== 'asc' && sortOrder.value !== 'desc') {
    sortOrder.value = 'asc';
  }
  handleQuery();
};

const toggleSortOrder = () => {
  sortOrder.value = sortOrder.value === 'asc' ? 'desc' : 'asc';
  handleQuery();
};

// 处理更多命令
const handleMoreCommand = (command) => {
  switch (command) {
    case 'download-template':
      handleImportTemplate();
      break;
    case 'import-data':
      handleImport();
      break;
    case 'export-data':
      handleExport();
      break;
    default:
      break;
  }
};

/**
 * 下载导入模板
 */
const handleImportTemplate = () => {
  proxy?.download('pro/flow/importTemplate', {}, `project_flow_template_${new Date().getTime()}.xlsx`);
};

/**
 * 导出数据
 */
const handleExport = () => {
  proxy?.download('pro/flow/export', {}, `project_flow_${new Date().getTime()}.xlsx`);
};

/**
 * 导入按钮操作
 */
const handleImport = () => {
  upload.title = '项目计划导入';
  upload.open = true;
  upload.isUploading = false;

  if (uploadRef.value) {
    uploadRef.value.clearFiles();
  }
};

/**
 * 文件上传中处理
 */
const handleFileUploadProgress = () => {
  upload.isUploading = true;
};

/**
 * 文件上传成功处理
 */
const handleFileSuccess = (response: any) => {
  upload.open = false;
  upload.isUploading = false;
  uploadRef.value?.clearFiles();
  // 导出结果弹出
  ElMessageBox.alert(response.msg, '导入结果', {
    dangerouslyUseHTMLString: true,
    confirmButtonText: '确定',
    type: 'info'
  });
  // 重新获取列表
  getList();
};

/**
 * 提交上传文件
 */
const submitFileForm = () => {
  uploadRef.value?.submit();
};

onMounted(() => {
  getList();
});
</script>

<style scoped>
.search-form {
  background: #f5f5f5;
  padding: 18px;
  border-radius: 4px;
  margin-bottom: 20px;
}

.search-form .el-form-item {
  margin-bottom: 12px;
}

.search-form .el-input,
.search-form .el-select {
  width: 200px;
}

.search-form .el-button {
  margin-left: 10px;
}

.icon-button {
  padding: 8px;
  margin: 0 2px;
}

.icon-button .el-icon {
  font-size: 16px;
}
</style>
